#include "stm32f10x.h"                  // Device header

void Encoder_Init_TIM2and4()
{
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2 | RCC_APB1Periph_TIM4,ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB | RCC_APB2Periph_GPIOA, ENABLE);			//开启ABP2上的GPIOB和A的时钟
	
	GPIO_InitTypeDef GPIO_InitStruct;
	GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IPU;														//上拉输入
	GPIO_InitStruct.GPIO_Pin = GPIO_Pin_6 |GPIO_Pin_7;										//开启PB6和7
	GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;												//频率50MHz
	GPIO_Init(GPIOB, &GPIO_InitStruct);
	
	GPIO_InitStruct.GPIO_Pin = GPIO_Pin_0 |GPIO_Pin_1;										//开启PA0和1
	GPIO_Init(GPIOA, &GPIO_InitStruct);
	
	//配置TIM2的时基单元
	TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
	TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;				//不分频
	TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;    //向上计数
	TIM_TimeBaseInitStruct.TIM_Period = 65535;                   		//自动重装值(arr)为65535
	TIM_TimeBaseInitStruct.TIM_Prescaler = 0;                       //不预分频
	TIM_TimeBaseInitStruct.TIM_RepetitionCounter = 0x00;            //不用重复计数器
	//写入TIM2和TIM4的时基单元
	TIM_TimeBaseInit(TIM2,&TIM_TimeBaseInitStruct);
	TIM_TimeBaseInit(TIM4,&TIM_TimeBaseInitStruct);
	
	//初始化输入捕获单元
	TIM_ICInitTypeDef TIM_ICInitStruct;
	TIM_ICInitStruct.TIM_Channel = TIM_Channel_1; 								//一号通道
	TIM_ICInitStruct.TIM_ICFilter = 0x0F;													//滤波
	TIM_ICInitStruct.TIM_ICPolarity = TIM_ICPolarity_Rising;			//上升沿触发
	TIM_ICInitStruct.TIM_ICPrescaler = TIM_ICPSC_DIV1;						//不分频
	TIM_ICInitStruct.TIM_ICSelection = TIM_ICSelection_DirectTI;  //使用TI1FP1
	TIM_ICInit(TIM2, &TIM_ICInitStruct);													//配置TIM2的1号通道
	TIM_ICInit(TIM4, &TIM_ICInitStruct);													//配置TIM4的1号通道
	
	TIM_ICInitStruct.TIM_Channel = TIM_Channel_2; 								//2号通道 TI2FP2
	TIM_ICInit(TIM2, &TIM_ICInitStruct);													//配置TIM2的2号通道
	TIM_ICInit(TIM4, &TIM_ICInitStruct);													//配置TIM4的2号通道
	
	TIM_EncoderInterfaceConfig(TIM2,TIM_EncoderMode_TI12,TIM_ICPolarity_Rising,TIM_ICPolarity_Rising);
	TIM_EncoderInterfaceConfig(TIM4,TIM_EncoderMode_TI12,TIM_ICPolarity_Rising,TIM_ICPolarity_Rising);
	
	TIM_SetCounter(TIM2,0);                                       //清零计时器
	TIM_SetCounter(TIM4,0);                                       //同上
	                                                             
	TIM_Cmd(TIM2, ENABLE);																				//开启定时器
	TIM_Cmd(TIM4, ENABLE);																				//开启定时器
}
/**/
int16_t Encoder_GetTIM4()
{
	int16_t Temp = TIM_GetCounter(TIM4);
	TIM_SetCounter(TIM4,0);
	return Temp;
}

int16_t Encoder_GetTIM2()
{
	int16_t Temp = TIM_GetCounter(TIM2);
	TIM_SetCounter(TIM2,0);
	return Temp;
}